import React, { Component } from "react";
import axios from "axios";
import PropTypes from "prop-types";

export class Header extends Component {
  state = {
    todoName: "",
  };

  static propTypes = {
    getTodoList: PropTypes.func.isRequired
  }

  // 在input上，敲了enter建，有内容，添加任务
  addTodo = async (e) => {
    if (e.keyCode === 13) {
      const name = this.state.todoName.trim();
      if (name) {
        // 添加任务请求
        await axios.post("http://localhost:5000/todos", { name, done: false });
        this.setState({ todoName: '' })
        this.props.getTodoList()
      }
    }
  };

  render() {
    return (
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          placeholder="What needs to be done?"
          autoFocus
          value={this.state.todoName}
          onChange={(e) => this.setState({ todoName: e.target.value })}
          onKeyUp={this.addTodo}
        />
      </header>
    );
  }
}

export default Header;
